<?php
include_once './application/application.php';
include_once './application/lib/messages.php';

function mb_trim($str) { return preg_replace( "/(^\s+)|(\s+$)/us", "", $str); } 

class Page_messages {
    public $action;
    public $error;
    public $messages;

    public function __construct() {
        $this->action = Arr::getValue( $_POST, 'action', false );
        DB::connect();
        if ( !DB::state() )
            $this->error = DB::getError();
        $this->init();
    }
    public function __destruct() {
    }

    public function init() {
        
    }
    public function readMessages() {
        $J              = new JSON();
        $J->page        = Arr::getValue($_POST, 'page', 1);
        $this->messages = Messages::get( $J->page );
        $J->messages    = ($this->messages) ? Messages::order($this->messages) : NULL;
        $J->numRows     = Messages::$numRows;
        $J->state       = 1;
        return $J;
    }
    private function call_get() {
        $J = $this->readMessages();
        
        return $J;
    }
    private function call_hide(){
        $J = new JSON();
        $J->id       = (int) $J->readVar( 'id' );
        $J->viewable = (int) $J->readVar( 'viewable' );
        $query = sprintf(
            "UPDATE `messages` SET `viewable` = %d WHERE id = %d LIMIT 1",
            $J->viewable,
            $J->id
        );
        if (  !DB::query($query)  ) return $J->error( DB::getError() );
        $J->state = 1;
        return $J;
    }
private function call_type(){
        $J       = new JSON();
        $J->id   = (int) $J->readVar('id');
        $res     = DB::query("SELECT type FROM messages WHERE id = $J->id LIMIT 1");

        $J->type = (int) Arr::getValue($res->fetch_array(MYSQLI_NUM), 0, Messages::$types['min']);
        // return $J->type;
        // return $J->error($J->type);
        $J->type++;

        if ($J->type > Messages::$types['max']) $J->type = Messages::$types['min'];
        if (  !DB::query("UPDATE `messages` SET type = $J->type WHERE id = $J->id LIMIT 1")  ) return $J->error( DB::getError() );

        $J->state = 1;
        return $J;
    }
    public function call( $method = FALSE ) {
        $method = ( $method ) ? $method : $this->action;
        $method = explode( '_', $method, 2 );
        $method = 'call_'.strtolower( $method[1] );
        if(method_exists($this, $method)) print call_user_func(array($this, $method));
    }
    public function call_update(){
        $J  = new JSON();
        $J->id        = (int)    $J->readVar('id');
        $J->title     = (string) mb_trim(  $J->readVar('title')  );
        $J->to_date   = (string) $J->readVar('to_date');
        $J->text      = (string) mb_trim(  $J->readVar('text')  );
        $J->type      = (int)    $J->readVar('type');
        $J->viewable  = (int)    $J->readVar('viewable');
        $query = sprintf(
            "UPDATE `messages`
                SET `title` = '$J->title', `to_date`='$J->to_date', `text`=' $J->text'
                WHERE id = $J->id LIMIT 1",
            DB::$mysqli->real_escape_string($J->title),
            $J->to_date,
            DB::$mysqli->real_escape_string($J->text),
            $J->id
        );
        if (!DB::query($query))
            return $J->error( DB::getError() );
        return $J;
    }
    public function call_insert(){
        $J = new JSON();
        $J->title     = (string) mb_trim(  $J->readVar('title')  );
        $J->to_date   = (string) $J->readVar('to_date');
        $J->text      = (string) mb_trim(  $J->readVar('text')  );
        $J->type      = (int)    $J->readVar('type');
        $J->viewable  = (int)    $J->readVar('viewable');
        $query = sprintf(
            "INSERT INTO `messages` (title, to_date, text, type, viewable) VALUES('$J->title', '$J->to_date', '$J->text', '$J->type', '$J->viewable')",
            DB::$mysqli->real_escape_string($J->title),
            $J->to_date,
            DB::$mysqli->real_escape_string($J->text),
            (int) $J->viewable
        );
        if (!DB::query($query))
            return $J->error( DB::getError() );
        $J->id = (int) DB::$mysqli->insert_id;
        return $J;
    }
    public function call_delete(){
        $J = new JSON();
        $J->id  = (int)  $J->readVar('id');
        $query = "DELETE FROM `messages` WHERE id = $J->id";
        if (!DB::query($query)) return $J->error( DB::getError() );
        return $J;
    }
    
    public function outPage() {
        $this->printOut( includeFile( APP_PAGE_PARTS . 'page_messages.php', $this->call_get() ) );
    }

    public function printOut( $content = '' ) {
        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm( true );
        $params = array(
            'leftmenu'  => Navbar::getVerticalBar( 'leftmenu' ),
            'content'   => $content ? $content : ''
        );

        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }
}

$page = new Page_messages();

Navbar::$expanded = 'lm-sys-web';

if ( $page->action ) print $page->call();
else {
    if ( !Auth::isLogged() ) reLocate ( 'index.php' );
    switch ( $_SERVER['QUERY_STRING'] ) {
    default:
        Navbar::$active = 'lm-messages';
        $page->outPage();
        break;
    }
}
?>